<template>
  <div class="app-container">
<br>
<br>
    <div class="header">
      <div style="display: flex;flex-direction: column;justify-content: end;width: 50%;">
        <el-form :model="query" ref="query" label-width="80px">
          <el-row :gutter=10>
            <el-col :span=16>
              <el-form-item label-width="250px" label="姓名/编号/电话(后四位)/身份证号" prop="name" >
                  <el-input v-model="query.name" placeholder="请输入姓名/编号/电话(后四位)/身份证号"/>
              </el-form-item>
            </el-col>
            <el-col :span=8>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="search" >搜索</el-button>
                <el-button @click="resetForm('query')">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- <el-card class="box-card" v-for="report in reports" :key="report.jobOfficeId"  >
        <div slot="header" class="clearfix">
          <span>{{ report.jobOfficeName }}</span>
        </div>
        <div class="text item">
          {{'候诊人数: ' + report.waitingCount }}
        </div>
        <div class="text item">
          {{'就诊人数: ' + report.doingCount }}
        </div>
      </el-card> -->
    </div>
    <el-button type="primary" @click="add">添加会员</el-button>
    <br>
    <br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    > 
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="编号" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="身份证号" width="160" align="center">
        <template slot-scope="scope">
          {{ scope.row.idCard }}
        </template>
      </el-table-column>
      <el-table-column label="性别" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.sex }}
        </template>
      </el-table-column>
      <el-table-column label="出生年月" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.birthday + ' ' }} {{ scope.row.birthdayType | birthdayTypeFilter }} 
        </template>
      </el-table-column>
      <el-table-column label="年龄" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.age }}
        </template>
      </el-table-column>
      <el-table-column label="入籍时长" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.joinDuration }}
        </template>
      </el-table-column>
      <el-table-column label="就诊状态" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.visitStatus }}
        </template>
      </el-table-column>
      <el-table-column label="会员等级" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.vipLevel }}
        </template>
      </el-table-column>
      <el-table-column label="就诊日期" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.visitDate }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" align="center" width="300" >
        <template slot-scope="scope">
          <el-dropdown size="medium" trigger="click" @command="optionPatient" >
            <el-button type="primary">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="composeValue(scope.row, 1)" >基础信息查询</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 2)" >基础信息修改</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 3)" >会员等级设置</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 4)" divided >会员就诊记录查询</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-button type="warning"  @click="toGuidance(scope.row)" size="small">挂号</el-button>
          <el-button type="primary"  @click="getInfo(scope.row)" size="small">详情</el-button>
          <el-button type="success"  @click="update(scope.row)" size="small">修改</el-button>
          <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="->, total, prev, pager, next"
      :total="this.total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="clickCurPage"
      >
    </el-pagination>
  <el-dialog title="会员详情" :visible.sync="infoVisible" width="1200px">
      <h2>会员信息</h2>
      <el-form ref="info" :model="info" label-width="120px">
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="编号">
              <el-input v-model="info.code" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="姓名">
              <el-input v-model="info.name" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="手机号">
              <el-input v-model="info.phone" @input="inputPhone" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="身份证号">
              <el-input v-model="info.idCard" @input="inputIdCard" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="年龄">
              <el-input v-model="info.age" type="Number" min=0 :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="性别">
              <el-select v-model="info.sex" placeholder="请选择" :disabled="true">
                <el-option
                  v-for="item in sexEnum"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="出生日期">
              <el-date-picker v-model="info.birthday" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" @change="changeBirthday" :disabled="true"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="农历/公历">
              <el-select v-model="info.birthdayType" placeholder="请选择" :disabled="true">
                <el-option
                  v-for="item in birthdayTypeEnum"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="来源">
              <el-select v-model="info.source" placeholder="请选择" :disabled="true">
                <el-option
                  v-for="item in sourceEnum"
                  :key="item.id"
                  :label="item.source"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="介绍人">
              <el-select v-model="info.introducer" placeholder="请选择" :disabled="true">
                <el-option
                  v-for="item in userEnum"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="距离(站)">
              <el-input v-model="info.distance" type="Number" min=0 :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <div v-for="(address, index) in info.addressList" :key="index">
            <el-row :gutter="10">
              <el-col :span=6 >
                <el-form-item label="省/市/区" label-width="80px">
                  <el-cascader
                    :disabled="true"
                    style="width: 300px"
                    size="large"
                    :options="options"
                    v-model="address.addressPre"
                    @change="handleChange">
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span=6 :offset=3>
                <el-form-item label="详细地址" label-width="80px">
                  <el-input v-model="address.addressInfo" style="width: 500px" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
  </el-dialog>

  <el-dialog :title="dialogTitle" :visible.sync="formVisible" :closeOnClickModal="false" width="1200px">
      <h2>会员信息</h2>
      <el-form ref="form" :model="form" label-width="120px" :rules="formRules">
        <el-row :gutter="10">
          <!-- <el-col :span=8 >
            <el-form-item label="编号">
              <el-input v-model="form.code" />
            </el-form-item>
          </el-col> -->
          <el-col :span=16 >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" @input="inputPhone" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" @input="inputIdCard" maxlength="18" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="年龄">
              <el-input v-model="form.age" type="Number" min=0 />
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option
                  v-for="item in sexEnum"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker v-model="form.birthday" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" @change="changeBirthday"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="农历/公历" prop="birthdayType">
              <el-select v-model="form.birthdayType" placeholder="请选择">
                <el-option
                  v-for="item in birthdayTypeEnum"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="来源" prop="source">
              <el-select v-model="form.source" placeholder="请选择">
                <el-option
                  v-for="item in sourceEnum"
                  :key="item.id"
                  :label="item.source"
                  :value="item.id"
                  @click.native="changeSource(item.id)"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="介绍人">
              <el-select v-model="form.introducer" placeholder="请选择" :disabled="introducerDisable">
                <el-option
                  v-for="item in userEnum"
                  :key="item.id"
                  :label="form.source === 1 ? item.code + ' - ' +item.name : item.jobNumber + ' - ' + item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8 >
            <el-form-item label="距离(站)" prop="distance">
              <el-input v-model="form.distance" type="Number" min=0 />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <div v-for="(address, index) in form.addressList" :key="index">
            <el-row :gutter="10">
              <el-col :span=1 >
                <el-button type="danger" icon="el-icon-delete" circle @click="deleteAddress(address, form.addressList)"></el-button>
              </el-col>
              <el-col :span=6 >
                <el-form-item label="省/市/区" label-width="80px" prop="addressPre">
                  <el-cascader
                    style="width: 300px"
                    size="large"
                    :options="options"
                    v-model="address.addressPre"
                    @change="handleChange">
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span=6 :offset=3>
                <el-form-item label="详细地址" label-width="80px" prop="addressInfo">
                  <el-input v-model="address.addressInfo" style="width: 500px"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" @click="addAddress">添加地址</el-button>
        </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      
  </el-dialog>
  </div>
</template>

<script>

import { getList, add, edit, del, getAllPatientList} from '@/api/patient'
import { getAllUserList} from '@/api/user'
import { getList as getSourceList} from '@/api/source'
import { regionData } from 'element-china-area-data'
import { guidanceWaitingNumber} from '@/api/guidance'



export default {
  filters: {
    birthdayTypeFilter(status) {
      const statusMap = ['', '阳', '阴']
      return statusMap[status]
    }
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) callback(new Error('请输入姓名')) 
      else callback()
    }
    const validatePhone = (rule, value, callback) => {
      if (!value) callback(new Error('请输入电话')) 
      else callback()
    }
    const validateIdCard = (rule, value, callback) => {
      if (!value) callback(new Error('请输入身份证号')) 
      else callback()
    }
    const validateSex = (rule, value, callback) => {
      if (!value) callback(new Error('请选择性别')) 
      else callback()
    }
    const validateBirthday = (rule, value, callback) => {
      if (!value) callback(new Error('请选择出生日期')) 
      else callback()
    }
    const validateBirthdayType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型')) 
      else callback()
    }
    const validateSource = (rule, value, callback) => {
      if (!value) callback(new Error('请选择来源')) 
      else callback()
    }
    const validateDistance = (rule, value, callback) => {
      if (!value) callback(new Error('请选择距离(站)')) 
      else callback()
    }
    const validateAddressPre = (rule, value, callback) => {
      var flag = false
      for (const address of this.form.addressList) {
        if(!address.addressPre || address.addressPre.length < 3) flag = true
      }
      if (flag) callback(new Error('地址不能为空')) 
      else callback()
    }
    const validateAddressInfo = (rule, value, callback) => {
      var flag = false
      for (const address of this.form.addressList) {
        if(!address.addressInfo || address.addressInfo === '') flag = true
      }
      if (flag) callback(new Error('地址不能为空')) 
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      info: {},
      form: {},
      dialogTitle: '添加会员',
      birthdayTypeEnum:[{id: 1, name: '公历'}, {id: 2, name: '农历'}],
      sourceEnum: [],
      userEnum: [],
      sexEnum: ["男", "女"],
      formRules: {
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        idCard: [{ required: true, trigger: 'blur', validator: validateIdCard }],
        sex: [{ required: true, trigger: 'blur', validator: validateSex }],
        birthday: [{ required: true, trigger: 'blur', validator: validateBirthday }],
        birthdayType: [{ required: true, trigger: 'blur', validator: validateBirthdayType }],
        source: [{ required: true, trigger: 'blur', validator: validateSource }],
        distance: [{ required: true, trigger: 'blur', validator: validateDistance }],
        addressPre: [{ required: true, trigger: 'blur', validator: validateAddressPre }],
        addressInfo: [{ required: true, trigger: 'blur', validator: validateAddressInfo }],
      },
      inputValue: '',
      options: regionData,
      selectedOptions: [],
      query: {},
      introducerDisable: true,
      reports: [],
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getList({currentPage: this.currentPage, pageSize: this.pageSize}).then(res=>{
        this.list = res.data.records
        console.log(this.list)
        this.list.forEach(item=>{
          item.age = new Date().getFullYear() - item.birthday.substring(0,4)
          item.addressList.forEach(address=>{
            var addressPreArr = address.address.split(' ')
            address.addressPre = [addressPreArr[0], addressPreArr[1], addressPreArr[2]]
            address.addressInfo = addressPreArr[3]
          })
        })
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
      getSourceList().then(sourceRes=>{
        this.sourceEnum = sourceRes.data
      })
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var deptId = loginInfo.loginDept.deptId
      var workAddressId = loginInfo.loginWorkAddress.id
      var jobOfficeId = loginInfo.loginJobOffice?loginInfo.loginJobOffice.jobOfficeId:undefined
      guidanceWaitingNumber({deptId: deptId, workAddressId: workAddressId, jobOfficeId: jobOfficeId}).then(res=> {
        this.reports = res.data
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    getInfo(row) {
      this.info = row
      if(this.info.source === 1) {
        this.introducerDisable = false
        getAllPatientList().then(res=>{
          console.log("res", res)
          this.userEnum = res.data
        })
      } else if(this.info.source === 2) {
        this.introducerDisable = false
        getAllUserList().then(res=>{
          this.userEnum = res.data
        })
      }
      this.infoVisible = true
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改会员'
      this.form = JSON.parse(JSON.stringify(row))
      if(this.form.source === 1) {
        this.introducerDisable = false
        getAllPatientList().then(res=>{
          console.log("res", res)
          this.userEnum = res.data
        })
      } else if(this.form.source === 2) {
        this.introducerDisable = false
        getAllUserList().then(res=>{
          this.userEnum = res.data
        })
      }
      this.formVisible = true
    },
    deleteInfo(scope) {
      console.log(scope.row)
      this.$confirm('确定删除该会员?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    add(row) {
      this.reset()
      this.dialogTitle = '添加会员'
      this.$set(this.form, 'addressList', [])
      this.formVisible = true
    },
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(this.form)
          this.form.addressList.forEach(address=>{
            address.address = address.addressPre[0] + ' ' + address.addressPre[1] + ' ' + address.addressPre[2] + ' ' + address.addressInfo
          })
          if(this.form.id) {  // update
            edit(this.form).then(res=>{
              console.log(res)
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/guidance/patient', name: "Patient"})
            }).catch(err=>{
              console.log(err)
            })
          } else {
            add(this.form).then(res=>{
              console.log(res)
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/guidance/patient', name: "Patient"})
            }).catch(err=>{
              console.log(err)
            })
          }
          
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    inputPhone() {
      var phone = this.form.phone
      // this.form.realPhone = JSON.parse(JSON.stringify(phone))
      // if(phone.length === 11) {
      //   this.form.phone = phone.substring(0, 3) + '****' + phone.substring(7, 11)
      // }
    },
    inputIdCard() {
      var idCard = this.form.idCard
      if(idCard.length === 18) {
        var ymd = idCard.substring(6, 14)
        this.$set(this.form, 'birthday', ymd.substring(0,4) + '-' + ymd.substring(4,6) + '-' + ymd.substring(6,8))
        this.$set(this.form, 'age', new Date().getFullYear() - ymd.substring(0,4))
      }
    },
    changeBirthday() {
      this.$set(this.form, 'age', new Date().getFullYear() - this.form.birthday.substring(0,4))
    },
    addAddress() {
      this.form.addressList.push({})
    },
    deleteAddress(address, list) {
      list.splice(list.indexOf(address), 1);
    },
    handleChange (address) {
      this.$set(this.form, 'addressPre', address)
    },
    search() {
      getList({currentPage: this.currentPage, pageSize: this.pageSize, name: this.query.name}).then(res=>{
        this.list = res.data.records
        this.list.forEach(item=>{
          item.age = new Date().getFullYear() - item.birthday.substring(0,4)
          item.addressList.forEach(address=>{
            var addressPreArr = address.address.split(' ')
            address.addressPre = [addressPreArr[0], addressPreArr[1], addressPreArr[2]]
            address.addressInfo = addressPreArr[3]
          })
        })
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    toGuidance(item) {
      console.log(item)
      this.$router.push({name: "GuidancePage", params: item});
    },
    changeSource(sourceId) {
      this.$set(this.form, 'introducer', null)
      if(sourceId === 1) {
        getAllPatientList().then(res=>{
          console.log("res", res)
          this.userEnum = res.data
          this.introducerDisable = false
        })
      } else if(sourceId === 2) {
        getAllUserList().then(res=>{
          this.userEnum = res.data
          this.introducerDisable = false
        })
      } else {
          this.introducerDisable = true
      }
    },
    composeValue(row, optType) {
      return {
        row,
        optType
      }
    },
    optionPatient(value) {
      if(value.optType == 1) {
        this.getInfo(value.row)
      } else {
        this.update(value.row)
      }
    },


  }
}
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  
  .text {
    font-size: 14px;
  }
  .item {
    margin-bottom: 18px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .box-card {
    width: 150px;
    margin-right: 10px;
  }

  .header {
    display: flex;
    flex-direction: row;
  }
</style>